<?php
/**
 * Created by fengkl
 * User: Administrator
 * Date: 2018年5月16日 11:12:52
 * 
 */

namespace app\common\logic;

use app\common\model\User;
use app\common\validate;
use function EasyWeChat\Kernel\data_get;
use think\Db;
use app\common\logic\WalletLogic;
use hyperjiang\BankCard;

class UserLogic 
{
    /**
     * 用户列表
     * @return mixed
     */
    public function getList($map,$order,$size)
    {
        $usermodel = new User();
        $info = $usermodel->getList($map,$order,$size);
        foreach ($info as $k => $v) {
            $v['ptel'] = model("User")->where('id', $v['us_pid'])->value('us_tel');
            $v['p_nickname'] = model("User")->where('id', $v['us_pid'])->value('us_nickname');
        }
//        halt($info);exit;
        return $info;
    }
    //完善用户信息
    //2018年6月30日 19:40:28
    //fkl
    public function complete($data){
        $where['id'] = $data['id']; 
        $data['us_bank_number'] = preg_replace('/[ ]/', '', $data['us_bank_number']);
        $bank_info = BankCard::info($data['us_bank_number']);
        //halt($data);
        if(empty($bank_info)){
            $rel['code'] = 0;
            $rel['msg'] = '银行卡号非法';
            return $rel;
        }  
        if($bank_info['bankName'] != '中国工商银行' && $bank_info['bankName'] != '中国农业银行' && $bank_info['bankName'] != '中国建设银行'  && $bank_info['bankName'] != '中国银行'){
            $rel['code'] = 0;
            $rel['msg'] = '银行卡号不属于四大银行';
            return $rel;
        }
        if($data['us_bank'] != $bank_info['bankName']){
            $rel['code'] = 0;
            $rel['msg'] = '银行卡号和银行不匹配';
            return $rel;
        }   
        unset($data['id']);           
        $usermodel = new User();
        $rell = $usermodel->editInfo($data,$where);
        //var_dump($rel);exit;
        if($rell){
            $rel['code'] = 1;
            $rel['msg'] = '修改成功！';
        }else{
            $rel['code'] = 0;
            $rel['msg'] = '您并没有作出修改！';
        }
        return $rel;


    }

    /**
     * 用户逻辑删除
     * author fengkl
     * time 2018年5月16日 17:37:23
     * @return mixed
     */
    public function deleteUser($id)
    {        
        $map['id'] = $id;
        $data['us_delete_status'] = 0;
        $usermodel = new User();
        $rel = $usermodel->deleteUser($map,$data);       
        //var_dump($info);exit;
        return $rel;
    }
    /**
     * 用户修改
     * @param $data
     * @return array
     */
    public function edit($data)
    {
        $id = $data['id'];
        $validate = validate('Verify');
        $rel = array();
        $rst = $validate->scene('editUser')->check($data);
        if (!$rst) {
            return ['code'=>0,'msg'=>$validate->getError()];
        }
        $data['us_head_pic'] = str_replace("\\", "/", $data['us_head_pic']);

        //  校验推荐人手机号
        if (!empty($data['us_pid_tel'])) {
            $ptel = $data['us_pid_tel'];
            $pid_tel = model('User')->where('us_tel', $ptel)->field('us_tel')->select();
//            halt($pid_tel);
            $pid_count = count($pid_tel);
            if ($pid_count == 0) {
                return ['code' => 0, 'msg' => '该推荐人不存在', 'wait' => 3];
            } else {

                if ($data['us_pid_tel']==$data['us_tel']){
                    return ['code' => 0, 'msg' => '自己不能推荐自己', 'wait' => 3];
                }
                //  推荐人id (推荐人id,不能是其下级)
                $tid = model('User')->where('us_tel', $data['us_pid_tel'])->value('id');

                // 查询该用户下面的 所有 id
                $tid_check = $this->getAllChildrenId($id);
                if (in_array($tid, $tid_check)) {
                    return ['code' => 0, 'msg' => '该推荐人是其下级用户，不可更改'];
                }else{
                    $data['us_pid'] = $tid;
                }
            }
        } else {
            $data['us_pid'] = 0;
        }
        // 验证手机号是否已存在
        $where['id'] = $data['id'];
        $tel = model("User")->where($where)->value('us_tel');
        if($tel !== $data['us_tel']){
            $count = model("User")->where('us_tel', $data['us_tel'])->count();
            if ($count) {
                return [
                    'code' => 0,
                    'msg' => '该手机号已存在',
                ];
            }
        }      
        unset($data['id']);           
        if ($data['us_pwd'] != "") {
            $data['us_pwd'] = encrypt($data['us_pwd']);
        } else {
            unset($data['us_pwd']);
        }
        
        $usermodel = new User();
        $rell = $usermodel->editInfo($data,$where);
        if($rell){
            $rel['code'] = 1;
            $rel['msg'] = '修改成功！';
        }else{
            $rel['code'] = 0;
            $rel['msg'] = '您并没有作出修改！';
        }
        return $rel;
    }
    /**
     * 用户自己修改,头像和昵称修改
     * author fengkl
     * time 2018年6月12日 12:54:50
     * @return mixed
     */
    public function selfedit($data)
    {      
        //var_dump($data);
        $validate = validate('Verify');
        $rel = array();
        $rst = $validate->scene('selfeditUser')->check($data);
        //var_dump($rst);exit;
        if (!$rst) {
            $rel['code'] = 0;
            $rel['msg'] = $validate->getError();
            return $rel;
        }
        if(empty($data['us_head_pic'])){
            unset($data['us_head_pic']);
        }
        $data['us_head_pic'] = str_replace("\\", "/", $data['us_head_pic']);
        //验证手机号是否已存在
        $where['id'] = $data['id'];   
        unset($data['id']);           
        $usermodel = new User();
        $rell = $usermodel->editInfo($data,$where);
        //var_dump($rel);exit;
        if($rell){
            $rel['code'] = 1;
            $rel['msg'] = '修改成功！';
        }else{
            $rel['code'] = 0;
            $rel['msg'] = '您并没有作出修改！';
        }
        return $rel;
    }
    //申请成为代理商
    public function subToVip($data){
        //halt($data);
        $Umodel = model('User');
        $map['id'] = $data['id']; 
        $the_us = $Umodel->where($map)->find(); 
        if($the_us['ca_id']){
            return [
                'code' => 0,
                'msg' => '上次申请正在审核，请不要重复提交',
            ];
        }
        if($the_us['gave_status'] < 1){
            $datas['gave_status'] = 1;
        }
        $datas['ca_id'] = $data['data']['ca_id'];
        $str_rel = strpos($the_us['ca_list'], $datas['ca_id']);
        if($str_rel !== false){
            //如果分类id列表包含该分类，返回
            return [
                'code' => 0,
                'msg' => '已拥有该分类的代理权，请勿再次申请'
            ];
        }
        $datas['us_addr_code'] = implode(',', $data['data']['us_addr_code']);
        $datas['us_addr_addr'] = $data['data']['province'].$data['data']['city'].$data['data']['area'];
        $datas['us_reason'] = $data['data']['us_reason'];
        $datas['us_apply_time'] = date('Y-m-d H:i:s');
        $rel = $Umodel->updateInfo($map,$datas);
        return [
                'code' => 1,
                'msg' => $rel,
            ];
    }

    /**
     * 用户添加
     */
    public function addUser($data)
    {
        $validate = validate('Verify');
        $rst = $validate->scene('addUser')->check($data);
        if (!$rst) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        if (array_key_exists('us_head_pic', $data) && $data['us_head_pic']) {
            $data['us_head_pic'] = str_replace("\\", "/", $data['us_head_pic']);
        } else {
            $data['us_head_pic'] = "/static/admin/img/head3.jpg";
        }

        if (empty($data['us_id_card'])){
            return ['code' => 0, 'msg' => '身份证号不能为空！'];
        }

        // 身份证验证
        if (is_idcard($data['us_id_card'])==false){
            return ['code' => 0, 'msg' => '身份证不符合规格！'];

        }



        //验证推荐人
        if ($data['ptel']) {
            $pinfo = model("User")->where(['us_type' => [2, 3]])->where('us_tel', $data['ptel'])->find();
            $data['t_us_type'] = $pinfo['us_type'];  // 推荐人角色类型
            $p_num = count($pinfo);
            if ($p_num == 1) {
                $data['us_pid'] = $pinfo['id'];   //推荐人ID
            } else {
                return ['code' => 0, 'msg' => '只有店主和运营中心可以分享哟！'];
            }
        } else {
            $data['us_pid'] = 0;  //推荐人不存在
            $data['t_us_type'] = '不存在'; //推荐人不存在无角色类型
        }
        //验证昵称
        if (!$data['us_nickname']) {
            return ['code' => 0, 'msg' => '昵称不能为空'];
        }
        //验证手机号是否已存在
        $count = model("User")->where('us_tel', $data['us_tel'])->count();
        if ($count) {
            return [
                'code' => 0,
                'msg' => '该手机号已被注册',
            ];
        }
        //工号生成
        $number = model("User")->order('id desc')->value('us_account');
        $lenth = strlen($number);
        if ($lenth == 12) {
            $bb = substr($number, -10);
            $cc = substr($number, 0, 2);
            $dd = $bb + 1;
            $new_number = $cc . $dd;
        } else {
            $new_number = 'SZ2018000001';
        }
        $data['us_account'] = $new_number;
        $data['us_add_time'] = date('Y-m-d H:i:s');

        //验证密码
        if (empty($data['us_pwd'])) {
            return [
                'code' => 0,
                'msg' => '请填写登录密码',
            ];
        }
        $data['us_pwd'] = encrypt($data['us_pwd']);

        //验证交易密码
        if (empty($data['us_pay_pwd'])) {
            return [
                'code' => 0,
                'msg' => '请填写交易密码',
            ];
        }

        $data['us_pay_pwd'] = encrypt($data['us_pay_pwd']);
//        if (array_key_exists('us_safe_pwd', $data)) {
//            $data['us_safe_pwd'] = encrypt($data['us_safe_pwd']);
//        }


        //操作
        unset($data['ptel']);
        unset($data['code']);
        //$wallet = new \app\common\logic\WalletLogic();
        $rell = model('User')->addUser($data);
        if ($rell) {
//            return $wallet->index($data['t_us_type'], $data['us_type'], $data['us_pid'], $rell);
            return ['code' => 1, 'msg' => '添加成功！'];
          // return $wallet->index($data['t_us_type'], $data['us_type'], $data['us_pid'], $rell);
        } else {
            return ['code' => 0, 'msg' => '添加失败！'];
        }

    }


    private function getAllChildrenId($id)
    {
        $ids = $this->getChildrenId($id) ?? [];
        $noHandleIds = $ids;
        while (!empty($noHandleIds)) {
            $id = array_shift($noHandleIds);
            $childrenIds = $this->getChildrenId($id);
            foreach ($childrenIds as $v) {
                array_push($ids, $v);
                array_push($noHandleIds, $v);
            }
        }
        return $ids;
    }

    private function getChildrenId($id)
    {
        return db('user')
            ->where('us_pid', $id)
            ->column("id");
    }

}